﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Security.Cryptography;
using System.Web.Configuration;
using MVCBootstrap.MongoDB.Web.Security;

namespace MVCBootstrap.Tests.MongoDB {

	public static class MembershipTestHelper {

		public static NameValueCollection GetSettings(String name) {
			var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

			// Add machine keys (for encrypted passwords).                                    
			var rng = new RNGCryptoServiceProvider();

			var validationKeyBuffer = new byte[64];
			rng.GetBytes(validationKeyBuffer);
			var validationKey = BitConverter.ToString(validationKeyBuffer).Replace("-", string.Empty);

			var decryptionKeyBuffer = new byte[32];
			rng.GetBytes(decryptionKeyBuffer);
			var decryptionKey = BitConverter.ToString(decryptionKeyBuffer).Replace("-", string.Empty);

			var machineKey = (MachineKeySection)config.GetSection("system.web/machineKey");
			machineKey.ValidationKey = validationKey;
			machineKey.Validation = MachineKeyValidation.SHA1;
			machineKey.DecryptionKey = decryptionKey;
			machineKey.Decryption = "AES";

			// Add the provider.           
			var membership = (MembershipSection)config.GetSection("system.web/membership");
			membership.DefaultProvider = name;
			var provider = new ProviderSettings(name, typeof(MongoDBMembershipProvider).AssemblyQualifiedName);
			membership.Providers.Clear();
			membership.Providers.Add(provider);

			config.Save(ConfigurationSaveMode.Modified);
			ConfigurationManager.RefreshSection("system.web/machineKey");
			ConfigurationManager.RefreshSection("system.web/membership");

			return new NameValueCollection {
                {"minRequiredNonAlphanumericCharacters", "0"},
                {"requiresUniqueEmail", "true"}
            };
		}
	}
}